package com.ice.base.util;

import com.ice.base.constant.HCNetSDK;
import com.ice.body.hardware.model.DeviceFace;
import com.ice.body.hardware.service.DeviceFaceService;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 人脸识别设备出门布防工具类
 */
@Slf4j
@Component
public class FaceCloseBfUtil {

    @Autowired
    private FMSGCallBackUtil fmsgCallBackUtil;
    @Resource
    private DeviceFaceService deviceFaceService;

    /**
     * 初始化布防
     * @throws Exception
     */
    public void faceCloseBf(HCNetSDK sdk){
        DeviceFace model = new DeviceFace();
        model.setDeviceType(1);
        ArrayList<DeviceFace> list = deviceFaceService.selectListByModel(model);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        HCNetSDK.NET_DVR_DEVICEINFO m_strDeviceInfo= new HCNetSDK.NET_DVR_DEVICEINFO();



        list.forEach(face->{
            int lUserID = sdk.NET_DVR_Login(face.getIp(),(short)Integer.parseInt(face.getPort()),face.getUserName(),face.getPwd(),m_strDeviceInfo);
            if (lUserID == -1){
                int result = sdk.NET_DVR_GetLastError();
                log.info("关门布防错误码================"+result);
                return;
            }
            // 启动布防
            SetupAlarmChanClose(lUserID,new NativeLong(-1));
        });
    }

    /**
     * 启动布防
     * @param lUserID
     */
    private void SetupAlarmChanClose(int lUserID,NativeLong lAlarmHandle) {

        // 尚未布防,需要布防
        if (lAlarmHandle.intValue() < 0){
            Pointer pUser = null;
            if (!HCNetSDK.INSTANCE.NET_DVR_SetDVRMessageCallBack_V31(fmsgCallBackUtil, pUser)){
                log.info("设置回调函数失败!");
            }
            HCNetSDK.NET_DVR_SETUPALARM_PARAM m_strAlarmInfo = new HCNetSDK.NET_DVR_SETUPALARM_PARAM();
            m_strAlarmInfo.dwSize=m_strAlarmInfo.size();
            m_strAlarmInfo.byLevel=1;
            m_strAlarmInfo.byAlarmInfoType=1;
            m_strAlarmInfo.write();
            int  x = HCNetSDK.INSTANCE.NET_DVR_SetupAlarmChan_V41(lUserID, m_strAlarmInfo);
            if (x == -1) {
                int result = HCNetSDK.INSTANCE.NET_DVR_GetLastError();
                log.info("关门布防失败错误码================"+result);
                log.info("关门人脸识别设备布防失败");
            }else{
                log.info("关门人脸识别设备布防成功");
            }
        }
    }

}